<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- 搜索框 -->
        <el-col :span="3">
          <el-input v-model="userInfo.username" placeholder="根据用户名搜索" />
        </el-col>
        <!-- 按钮 -->
        <el-col :span="1">
          <el-button @click="onClear">清空</el-button>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" class="search-btn" @click="onSearch"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="1" :offset="17" class="add-user">
          <el-button type="success" @click="onAdd">新增用户</el-button>
        </el-col>
      </el-row>
      <el-alert type="info" show-icon :closable="false">
        <template> 共{{ total }}条记录 </template>
      </el-alert>
      <!-- 表格 -->
      <el-table
        :data="userList"
        style="width: 100%"
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" label="序号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="permission_group_title" label="权限组名称" />
        <el-table-column prop="role" label="角色" />
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              plain
              type="primary"
              icon="el-icon-edit"
              circle
              @click="onEdit(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              plain
              v-if="scope.row.id !== 2"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="onDelete(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :background="true"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户组件的弹层 -->
      <user-add
        :showAddUser="addUserVisible"
        :text="text"
        :pageTitle="pageTitle"
        :formBase="formBase"
        :PermissionGroupsList="PermissionGroupsList"
        @handleCloseModal="handleCloseModal"
        @load-user-list="loadUserList"
      />
    </el-card>
  </div>
</template>

<script>
import { list, remove } from '@/api/base/users.js'
import { simple } from '@/api/base/permissions.js'
import userAdd from '../components/user-add.vue'
export default {
  components: { userAdd },
  data () {
    return {
      // 获取用户列表的参数
      userInfo: {
        username: '',
        page: 1, // 当前的页数
        pagesize: 10
      },
      // 表格数据
      userList: [],
      total: 1, // 列表总数
      addUserVisible: false, // 控制添加用户组件的弹层
      text: '', // 弹层标题文本 添加 编辑
      pageTitle: '用户',
      // 表单弹层组件的数据
      formBase: {
        username: '',
        email: '',
        password: '',
        role: '',
        permission_group_id: '',
        phone: '',
        avatar: '',
        introduction: null,
        sex: ''
      },
      // 权限组列表
      PermissionGroupsList: []
    }
  },

  created () {
    this.loadUserList()
  },

  methods: {
    // 加载用户列表
    async loadUserList () {
      try {
        const res = await list(this.userInfo)
        console.log(res)
        this.userList = res.data.list
        this.total = res.data.counts
      } catch (err) {
        this.$message.error('网络异常')
      }
    },
    // 选择的每一页的数量size
    handleSizeChange (newSize) {
      // console.log(`每页 ${newSize} 条`)
      this.userInfo.pagesize = newSize
      this.loadUserList()
    },
    // 选择切换当前页page
    handleCurrentChange (newPage) {
      // console.log(`当前页: ${newPage}`)
      this.userInfo.page = newPage
      this.loadUserList()
    },
    // 点击清空按钮
    onClear () {
      this.userInfo.username = ''
      this.loadUserList()
    },
    // 点击搜索按钮
    onSearch () {
      this.loadUserList()
    },
    // 点击新增用户
    async onAdd () {
      this.text = '创建'
      this.formBase.password = '' // 点击新增，密码赋值为空字符串，显示密码框
      this.addUserVisible = true // 打开弹层
      try {
        const res = await simple() // 获取权限组列表数据
        // console.log(res)
        this.PermissionGroupsList = res.data
      } catch (err) {
        this.$message.error('获取权限组数据失败')
      }
    },
    // 点击编辑
    async onEdit (row) {
      this.text = '编辑'
      this.addUserVisible = true // 打开弹层
      try {
        const res = await simple() // 获取权限组列表数据
        // console.log(res)
        this.PermissionGroupsList = res.data
      } catch (err) {
        this.$message.error('获取权限组数据失败')
      }
      console.log(row)
      this.formBase.id = row.id
      // 为编辑表单赋值
      this.formBase.username = row.username
      this.formBase.email = row.email
      this.formBase.password = null
      this.formBase.role = row.role
      // this.formBase.permission_group_title = row.permission_group_title
      this.formBase.permission_group_id = row.permission_group_id
      this.formBase.phone = row.phone
      this.formBase.avatar = row.avatar
      this.formBase.introduction = row.introduction
    },
    // 弹层关闭
    handleCloseModal () {
      this.addUserVisible = false // 关闭弹层
      // 清空表单
      this.formBase.username = ''
      this.formBase.email = ''
      this.formBase.password = null
      this.formBase.role = ''
      this.formBase.permission_group_title = ''
      this.formBase.phone = ''
      this.formBase.avatar = ''
      this.formBase.introduction = ''
      this.formBase.id = null
    },
    // 点击删除
    onDelete (row) {
      // console.log(row.id)
      this.$confirm('即将执行永久删除操作，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await remove({ id: row.id })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.loadUserList() // 删除成功 重新加载页面
          } catch (err) {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style scoped lang="less">
.text {
  font-size: 14px;
}
.item {
  padding: 18px 0;
}
.box-card {
  margin: 20px 20px;
}
.search-btn {
  margin-left: 20px;
}
/deep/.cell {
  text-align: center !important;
}
.el-alert {
  margin: 20px 0;
}
/deep/.el-alert__icon.is-big {
  font-size: 16px !important;
}
/deep/.el-alert .el-alert__description {
  margin: 0 !important;
  font-size: 13px !important;
}
.el-table {
  margin-bottom: 20px;
}
.el-pagination {
  text-align: right;
}
</style>
